import asyncio
import cv2
import requests
import re
import numpy as np

import time
from rapidfuzz import fuzz
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

params = [cv2.IMWRITE_JPEG_QUALITY, 50]  # ratio:0~100

# 连接设备
dev = connect_device('android:///')
print(dev)
poco = AndroidUiautomationPoco(use_airtest_input=True,
                               screenshot_each_action=False)
screen = dev.snapshot()
height, width, channels = screen.shape
# 获取屏幕分辨率
# width, height = poco.get_screen_size()

# 向下滑动一次（从屏幕高度70%处滑动到30%处）

end_point = (width / 2, height * 0.3)  # 中点偏下位置
start_point = (width / 2, height * 0.7)  # 中点偏上位置


def max_option_match(input_string, string_list):
    # 初始化最大匹配度和索引
    max_match_ratio = 0
    max_match_index = -1

    for index, compare_string in enumerate(string_list):
        # 使用fuzz.ratio方法计算两个字符串的匹配度
        match_ratio = fuzz.ratio(input_string, compare_string)

        # 如果当前匹配度大于已记录的最大匹配度，则更新最大匹配度和索引
        if match_ratio > max_match_ratio:
            max_match_ratio = match_ratio
            max_match_index = index
    # 返回匹配率和index
    return max_match_ratio, max_match_index


def touch_target(text: str, raw_list: list, box: list):
    _, i = max_option_match(text, raw_list)
    # i = raw_list.index(text)
    top_left_x = int(box[i][0][0])
    top_left_y = int(box[i][0][1])
    bottom_right_x = int(box[i][2][0])
    bottom_right_y = int(box[i][2][1])
    touch(((top_left_x + bottom_right_x) // 2,
           (top_left_y + bottom_right_y) // 2))


if __name__ == '__main__':
    cv2.namedWindow("Image Window", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("Image Window", 480, 640)
    while True:
        screen = dev.snapshot()
        # 灰度图
        gray = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
        # 二值化
        _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
        cv2.imshow("Image Window", screen)
        # cv2.imshow("binary", binary)
        cv2.imwrite("binary.png", binary)
        cv2.imwrite("screen.png", screen)
        # # 腐蚀、膨胀
        # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
        # dilated = cv2.dilate(binary, kernel, iterations=1)
        # eroded_img = cv2.erode(binary, kernel, iterations=1)
        ret, img_bytes = cv2.imencode(".png", binary, params)  # 将裁剪的cv2格式转成jpg
        image_in_bytes = img_bytes.tobytes()
        # screen = cv2.imread("screen.png")
        # with open("binary.png", "rb") as f:
        #     image_in_bytes = f.read()
        resp = requests.post(url='http://223.68.11.42:8211/ocr',
                             files={"imgbin": image_in_bytes})
        raw_list, box = resp.json()
        pos = exists(Template(r'./img/hongbao.png', threshold=0.7))
        for i in range(len(box)):
            # print(temp0[i], temp1[i])
            top_left_x = int(box[i][0][0])
            top_left_y = int(box[i][0][1])
            bottom_right_x = int(box[i][2][0])
            bottom_right_y = int(box[i][2][1])
            print((top_left_x, top_left_y), (bottom_right_x, bottom_right_y),
                  raw_list[i])
            cv2.rectangle(screen, (top_left_x, top_left_y),
                          (bottom_right_x, bottom_right_y), (0, 255, 0), 2)
        if '开宝箱得金币' in raw_list:
            print('开宝箱得金币')
            touch_target('开宝箱得金币', raw_list, box)
            keyevent("back")
            continue
        elif '邀请好友立赚高额现金' in raw_list:
            keyevent("back")
            continue
        elif '去打卡' in raw_list:
            touch_target('去打卡', raw_list, box)
            continue

        elif '领取晚餐补贴' in ''.join(raw_list):
            touch_target('领取晚餐补贴', raw_list, box)
            continue
        elif pos:
            print(pos)
            touch(Template(r'./img/hongbao.png', threshold=0.7))
        else:
            swipe(start_point, end_point)
            sleep(1)
        # 显示
        # cv2.imwrite("binary.png", binary)
        # cv2.imwrite("screen.png", screen)
        # cv2.imwrite("eroded_img.png", eroded_img)
        # cv2.imwrite("dilated.png", dilated)
        # (350, 585) (446, 615)
        # touch((398, 600 + y))
        # cv2.imshow("dilated", dilated)
        # cv2.imshow("erode", eroded_img)
        # 按下任意键继续显示下一帧，ESC键退出循环
        if cv2.waitKey(1) == 27:
            break
        # poco(type="X.UFS").swipe([-0.06, -0.3])
        # sleep(1)

# temp = [[
#     '1.《嘉禾八景图》是元代著名画家', '的传世名作，描绘了家乡浙江嘉兴的景', '色，为人"抗简孤洁"，另有名作《秋江渔', '隐图》',
#     '《渔父图》等。', '-10', 'A.曹知白', 'B.吴镇'
# ],
#         [[[53.0, 42.0], [427.0, 42.0], [427.0, 65.0], [53.0, 65.0]],
#          [[53.0, 76.0], [487.0, 76.0], [487.0, 100.0], [53.0, 100.0]],
#          [[53.0, 109.0], [486.0, 109.0], [486.0, 133.0], [53.0, 133.0]],
#          [[52.0, 142.0], [117.0, 142.0], [117.0, 169.0], [52.0, 169.0]],
#          [[135.0, 144.0], [283.0, 144.0], [283.0, 169.0], [135.0, 169.0]],
#          [[297.0, 183.0], [374.0, 183.0], [374.0, 195.0], [297.0, 195.0]],
#          [[78.0, 271.0], [184.0, 271.0], [184.0, 299.0], [78.0, 299.0]],
#          [[80.0, 354.0], [160.0, 354.0], [160.0, 380.0], [80.0, 380.0]]]]
# temp0, temp1 = temp
# for i in range(len(temp0)):
#     # print(temp0[i], temp1[i])
#     top_left_x = int(temp1[i][0][0])
#     top_left_y = int(temp1[i][0][1])
#     bottom_right_x = int(temp1[i][2][0])
#     bottom_right_y = int(temp1[i][2][1])
#     print((top_left_x, top_left_y), (bottom_right_x, bottom_right_y))
#     cv2.rectangle(screen, (top_left_x, top_left_y),
#                   (bottom_right_x, bottom_right_y), (0, 255, 0), 2)
#     # (53, 42) (427, 107)
# while True:
#     # 显示
#     cv2.imshow("binary.png", screen)
#     # 按下任意键继续显示下一帧，ESC键退出循环
#     if cv2.waitKey(1) == 27:
#         break
